﻿using System.Collections.Generic;
using System.Linq;
using NHibernate.Criterion;

namespace ShopSpace.Core.Repositories.Impl
{
	internal class PersonRepository : RepositoryBase<Person>, IPersonRepository
	{
		#region IPersonRepository Members

		public Person GetByUsername(int portalId, string username)
		{
			return this.GenericDAO.FindFirst<Person>(x => x.Username == username && x.PortalId == portalId);
		}

		public IList<Person> ListByPortal(int portalId)
		{
			var query = this.GenericDAO.AsQueryable<Person>()
				.Where(x => x.PortalId == portalId)
				.OrderBy(x => x.DisplayName);
			return query.ToList<Person>();
		}

		public IList<Person> ListAvailableForProject(Project project)
		{
			DetachedCriteria alreadOnProject = DetachedCriteria.For<ProjectPerson>()
				.Add(Expression.Eq("Project.Id", project.Id))
				.SetProjection(Projections.Property("Person.Id"));

			DetachedCriteria criteria = DetachedCriteria.For<Person>()
				.Add(Subqueries.PropertyNotIn("Id", alreadOnProject))
				.Add(Expression.Eq("PortalId", project.PortalId))
				.AddOrder(Order.Asc("DisplayName"));

			return this.GenericDAO.ListbyCriteria<Person>(criteria);

			//// When NHibernate.Linq catches up...
			//var query = from p in this.GenericDAO.AsQueryable<Person>()
			//            where (!(from pp in this.GenericDAO.AsQueryable<ProjectPerson>()
			//                           where pp.Project == project
			//                           select pp.Person.Id).Contains(p.Id))
			//            && p.PortalId == project.PortalId
			//            orderby p.DisplayName
			//            select p;
			//return query.ToList<Person>();
		}

		#endregion
	}
}